package com.eostoken.eos_wallet.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.FragmentUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.JsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.listener.OnLoadMoreListener;
import com.eostoken.eos_wallet.R;
import com.eostoken.eos_wallet.base.BaseFragment;
import com.eostoken.eos_wallet.bean.AccountInfo;
import com.eostoken.eos_wallet.bean.BillBean;
import com.eostoken.eos_wallet.bean.TransferDataBean;
import com.eostoken.eos_wallet.eosnet.common.Params;
import com.eostoken.eos_wallet.mvp.mode.BillModel;
import com.eostoken.eos_wallet.mvp.presenter.BillPresenterImpl;
import com.eostoken.eos_wallet.mvp.view.BillView;
import com.eostoken.eos_wallet.ui.activity.MoneyReceivingQRCodeActivity;
import com.eostoken.eos_wallet.ui.adapter.BillAdapter;
import com.eostoken.eos_wallet.ui.fragmentfactory.FragmentFactory;
import com.eostoken.eos_wallet.utils.Constants;
import com.eostoken.eos_wallet.utils.WalletUtils;
import com.google.gson.reflect.TypeToken;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.qmuiteam.qmui.widget.QMUITopBarLayout;
import com.qmuiteam.qmui.widget.pullLayout.QMUIPullLayout;
import com.qmuiteam.qmui.widget.pullLayout.QMUIPullLoadMoreView;
import com.qmuiteam.qmui.widget.pullLayout.QMUIPullRefreshView;
import com.qmuiteam.qmui.widget.tab.QMUITabBuilder;
import com.qmuiteam.qmui.widget.tab.QMUITabIndicator;
import com.qmuiteam.qmui.widget.tab.QMUITabSegment;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.eostoken.eos_wallet.utils.Constants.BILL;
import static com.eostoken.eos_wallet.utils.Constants.EXTRA_TRANSACTION_ID;
import static com.eostoken.eos_wallet.utils.Constants.EXTRA_TRANSACTION_LIST;
import static com.eostoken.eos_wallet.utils.Constants.TRANSACTION;
import static com.eostoken.eos_wallet.utils.Constants.TRANSACTION_DETAILS;

public class WalletFunctionFragment extends BaseFragment<BillModel, BillView, BillPresenterImpl> implements BillView {
    @BindView(R.id.tabSegment)
    QMUITabSegment mTabSegment;
    @BindView(R.id.topbar)
    QMUITopBarLayout topbar;
    @BindView(R.id.proceedsBtn)
    Button proceedsBtn;
    @BindView(R.id.transferAccountsBtn)
    Button transferAccountsBtn;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.refreshView)
    QMUIPullRefreshView refreshView;
    @BindView(R.id.loadMoreView)
    QMUIPullLoadMoreView loadMoreView;
    @BindView(R.id.pull_layout)
    QMUIPullLayout pullLayout;
    @BindView(R.id.line1)
    View line1;
    @BindView(R.id.bottomBtnLayout)
    LinearLayout bottomBtnLayout;

    private String[] arr;
    private String accountName;
    private BillBean billBean;
    private BillAdapter billAdapter;
    private int pos = -1;
    private int offset = -50;
    private int classify = 0;//0:全部；1：转出；2：转入；3：失败
    private List<BillBean> allBillBeanList = new ArrayList<>();
    private List<BillBean.ActionsBean> allActionsList = new ArrayList<>();
    private List<BillBean.ActionsBean> outActionsList = new ArrayList<>();
    private List<BillBean.ActionsBean> intoActionsList = new ArrayList<>();
    private QMUIPullLayout.PullAction mPullAction;
    private boolean isTransactionList = false;

    @Override
    protected int getContentLayout() {
        return R.layout.activity_wallet_function;
    }

    @Override
    protected void initData() {
        arr = new String[]{getString(R.string.str_all), getString(R.string.str_out)
                , getString(R.string.str_into), getString(R.string.str_fail)};
        Bundle bundle = getArguments();
        isTransactionList = bundle.getBoolean(EXTRA_TRANSACTION_LIST, false);
        accountName = WalletUtils.getCurrentAccountName();
        loadMore(false);
    }

    @Override
    protected void initView(View contentView) {
        topbar.setTitle(StringUtils.getString(R.string.str_transaction_record));
        topbar.addLeftBackImageButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        isTransactionListView();
        initTabAndPager();
        initRecyclerView();
        initLoadMore();
    }

    private void isTransactionListView() {
        mTabSegment.setVisibility(isTransactionList ? View.GONE : View.VISIBLE);
        line1.setVisibility(isTransactionList ? View.GONE : View.VISIBLE);
        bottomBtnLayout.setVisibility(isTransactionList ? View.GONE : View.VISIBLE);
    }

    private void initRecyclerView() {
        billAdapter = new BillAdapter(R.layout.bill_item, accountName);
        billAdapter.setAnimationEnable(true);
        recyclerView.setAdapter(billAdapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL));
        // 设置点击事件
        billAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                String orderID = (String) view.getTag(R.id.OrderID);
                String quantity = (String) view.getTag(R.id.quantity);
                LogUtils.dTag("TransactionDetailsFragment==", " orderID = " + orderID);
                Fragment fragment = FragmentFactory.getInstatic().getFragment(TRANSACTION_DETAILS);
                Bundle bundle = new Bundle();
                bundle.putString(EXTRA_TRANSACTION_ID, orderID);
                bundle.putString("quantity", quantity);
                fragment.setArguments(bundle);
                FragmentUtils.replace(getFragmentManager(), fragment, R.id.frag_container, "transaction", true);
            }
        });
    }

    private void initTabAndPager() {
        QMUITabBuilder builder = mTabSegment.tabBuilder().setGravity(Gravity.CENTER);
        for (int i = 0; i < arr.length; i++) {
            mTabSegment.addTab(builder.setText(arr[i]).build(getActivity()));
        }
        mTabSegment.setMode(QMUITabSegment.MODE_FIXED);
        int indicatorHeight = QMUIDisplayHelper.dp2px(getActivity(), 2);
        mTabSegment.setIndicator(new QMUITabIndicator(indicatorHeight, false, false));
        mTabSegment.selectTab(0);
        mTabSegment.addOnTabSelectedListener(new QMUITabSegment.OnTabSelectedListener() {
            @Override
            public void onTabSelected(int index) {
                classify = index;
                switch (classify) {
                    case 0://全部
                        billAdapter.setNewData(allActionsList);
                        break;
                    case 1://转出
                        billAdapter.setNewData(outActionsList);
                        break;
                    case 2://转入
                        billAdapter.setNewData(intoActionsList);
                        break;
                    case 3://失败
                        billAdapter.setNewData(null);
                        break;
                    default://全部
                        billAdapter.setNewData(allActionsList);
                }

            }

            @Override
            public void onTabUnselected(int index) {

            }

            @Override
            public void onTabReselected(int index) {
            }

            @Override
            public void onDoubleTap(int index) {
                mTabSegment.clearSignCountView(index);
            }
        });
    }


    private void loadMore(boolean isLoadMore) {
        if (isLoadMore) {
            offset -= 50;
        } else {
            offset = -50;
            allBillBeanList.clear();
            allActionsList.clear();
            outActionsList.clear();
            intoActionsList.clear();
        }
        presenter.requestKeyActions(Params.getActionsPamars(pos, offset, accountName));
    }

    /**
     * 初始化加载更多
     */
    private void initLoadMore() {
        pullLayout.setActionListener(new QMUIPullLayout.ActionListener() {
            @Override
            public void onActionTriggered(@NonNull QMUIPullLayout.PullAction pullAction) {
                boolean isLoadMore = false;
                if (pullAction.getPullEdge() == QMUIPullLayout.PULL_EDGE_TOP) {
                    isLoadMore = false;
                } else if (pullAction.getPullEdge() == QMUIPullLayout.PULL_EDGE_BOTTOM) {
                    isLoadMore = true;
                }
                mPullAction = pullAction;
                loadMore(isLoadMore);
            }
        });
        billAdapter.getLoadMoreModule().setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                loadMore(true);
            }
        });
        billAdapter.getLoadMoreModule().setAutoLoadMore(true);
        //当自动加载开启，同时数据不满一屏时，是否继续执行自动加载更多(默认为true)
        billAdapter.getLoadMoreModule().setEnableLoadMoreIfNotFullPage(false);
    }

    @OnClick({R.id.proceedsBtn, R.id.transferAccountsBtn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.proceedsBtn:
                Intent intent = new Intent(getActivity(), MoneyReceivingQRCodeActivity.class);
                ActivityUtils.startActivity(intent);
                break;
            case R.id.transferAccountsBtn:
                Fragment fragment = FragmentFactory.getInstatic().getFragment(TRANSACTION);
                Bundle bundle = new Bundle();
                fragment.setArguments(bundle);
                FragmentUtils.replace(getFragmentManager(), fragment, R.id.frag_container, "transfer", true);
                break;
        }
    }

    @Override
    public void updateView(Object data, int responseSuccessCode) {
        switch (responseSuccessCode) {
            case BILL:
                if (mPullAction != null) {
                    pullLayout.finishActionRun(mPullAction);
                }
                if (data != null) {
                    allBillBeanList.clear();
                    intoActionsList.clear();
                    outActionsList.clear();
                    allActionsList.clear();
                    billBean = (BillBean) data;
                    allBillBeanList.add(billBean);
                    List<BillBean.ActionsBean> actions = billBean.getActions();
                    List<BillBean.ActionsBean> actionsList = new ArrayList<>();
                    Collections.reverse(actions);
                    for (int i = 0; i < actions.size(); i++) {
                        BillBean.ActionsBean actionsBean = actions.get(i);
                        BillBean.ActionsBean.ActionTraceBean actionTraceBean = actionsBean.getAction_trace();
                        BillBean.ActionsBean.ActionTraceBean.ReceiptBean receiptBean = actionTraceBean.getReceipt();
                        String receiver = receiptBean.getReceiver();
                        if (ObjectUtils.equals(accountName, receiver)) {
                            BillBean.ActionsBean.ActionTraceBean.ActBean actBean = actionTraceBean.getAct();
                            if (ObjectUtils.equals("transfer", actBean.getName())) {
                                try {
                                    LogUtils.dTag("actBean==", actBean.getData().toString());
                                    TransferDataBean dataBean = GsonUtils.fromJson(GsonUtils.toJson(actBean.getData()), new TypeToken<TransferDataBean>() {
                                    }.getType());
                                    String to = dataBean.getTo();
                                    if (ObjectUtils.equals(accountName, to)) {
                                        if (classify == 2) {
                                            actionsList.add(actionsBean);
                                        }
                                        intoActionsList.add(actionsBean);
                                    } else {
                                        if (classify == 1) {
                                            actionsList.add(actionsBean);
                                        }
                                        outActionsList.add(actionsBean);
                                    }
                                    if (classify == 0) {
                                        actionsList.add(actionsBean);
                                    }
                                    allActionsList.add(actionsBean);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            } else {
                                actions.remove(actionsBean);
                            }
                        }
                    }
                    if (actionsList.size() > 0) {
                        billAdapter.setList(actionsList);
                        billAdapter.getLoadMoreModule().loadMoreComplete();
                        break;
                    }
                }
                billAdapter.getLoadMoreModule().loadMoreEnd();
                break;
        }

    }

    @Override
    public void onFailure(Object data, int responseFailCode) {
        switch (responseFailCode) {
            case BILL:
                billAdapter.getLoadMoreModule().loadMoreEnd();
                ToastUtils.showShort((String) data);
                if (mPullAction != null) {
                    pullLayout.finishActionRun(mPullAction);
                }
                break;
        }
    }

    @Override
    public BillModel createModel() {
        return new BillModel();
    }

    @Override
    public BillView createView() {
        return this;
    }

    @Override
    public BillPresenterImpl createPresenter() {
        return new BillPresenterImpl(getActivity());
    }

    @Override
    public void finishRefresh() {

    }

    @Override
    public void onResume() {
        super.onResume();
        isDataInitiated = false;
        loadMore(false);
    }
}
